<?php

class Page extends Component {
	public $params = array (
		'title',
		'style',
		'template',
		'editFormTemplate'
	);
	
	public static $actions = array (
		'editFormSave'
	);
	
	public $positions = false;
		
	function __construct ($id = false, $params = array ())  {
		$this->id = $id;
		
		if ($this->id !== false) {
			$this->load ();
		}
		else {
			foreach ($params as $key=>$value) {
				$this->{$key} = $value;
			}
		}
	}
		
	function createTable () {
		global $dbh;
  
  		$tableName = get_class ($this);
		
		$query = <<<QUERY
CREATE TABLE `{$tableName}` (
  `id` char(32) not null,
  `title` varchar(255) NOT NULL,
  `style` varchar(50),
  `template` varchar(50),
  `editFormTemplate` varchar(50),
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
QUERY;
		$dbh->exec ($query);

		return true;
	}
	
	function loadPositions () {
		global $dbh;
		
		$query = new ObjLib\Query (array (
			'tables' => array ('Page', 'Position'),
			'relations' => array ('Has'),
			'where' => "level0.id = {$dbh->quote ($this->id)}",
			'returnBy' => 'title'
		));
		$this->positions = $query->select ();
	}
	
	function assignComponent ($component, $title, $template = false) {
		global $dbh;
		
		$query = new ObjLib\Query (array (
			'tables' => array ('Page', 'Position'),
			'relations' => 'Has',
			'where' => "level0.id = {$dbh->quote ($this->id)} and level1.title = {$dbh->quote ($title)}"
		));

		$pos = $query->select ();
		if (count ($pos) > 0) {
			$pos = $pos[0];							
			$pos->title = $title;
			$pos->assignComponent ($component, $template);
			$pos->save ();
		}
		else {
			$pos = new Position (false, array ('title' => $title));
			$pos->assignComponent ($component, $template);
			$pos->save ();
			PageHasPosition::relate ($this, $pos);
		}

	}
};

?>